//
//  HMSinaSelectImageController.swift
//  ZJCSina
//
//  Created by 朱建超 on 16/11/24.
//  Copyright © 2016年 itHeiMa. All rights reserved.
//

import UIKit

let row : CGFloat = 3
let itemJianJu : CGFloat = 4
let selectImageWidth = (UIScreen.main.bounds.width - (row + 1) * itemJianJu) / row

//图片的最大数量
private let maxImageCount = 9

private let reuseIdentifier = "Cell"

class HMSinaSelectImageController: UICollectionViewController {

    //定义图片数组
    lazy var imageArray : [UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(SelectImageCell.self, forCellWithReuseIdentifier: reuseIdentifier)


        
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
 
        var count : Int
        
        if self.imageArray.count == maxImageCount {
            count = 0
        }else{
        
            count = 1
        }
        return self.imageArray.count + count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SelectImageCell
    
        cell.backgroundColor = randomColor()
    
        //6、设置代理
        cell.delegate = self
        
        //判断，如果加载的是最后一条数据就特殊处理
        if indexPath.item == self.imageArray.count {
            //给最后一个cell赋值
            cell.image = nil
        }else{
        
            cell.image = self.imageArray[indexPath.item]
        }
        
        return cell
    }


}

//MARK:3、遵守cell的协议  实现协议的放法
extension HMSinaSelectImageController : SelectImageCellDelegate{

    func chooseImage(cell : SelectImageCell?) {
        
        print("添加")
        //modal 图片选择控制器
        let pickerController = UIImagePickerController()
        
        //设置picker的代理
        pickerController.delegate = self
        
        //是否允许编辑
//        pickerController.allowsEditing = true
        //跳转
        self.present(pickerController, animated: true) {
            
             
            
        }
        
    }

    func deleteImage(cell : SelectImageCell) {
        
        print("删除")
        //根据被点击的cell，通过collectionView获取对应的indexPath
        guard let indexPath = collectionView?.indexPath(for: cell) else{
        
            return
        }
        
        //在数组中删除对应的图片
        self.imageArray.remove(at: indexPath.item)
        
        //刷新数据
        self.collectionView?.reloadData()
        
    }
    
}

//MARK:遵守picker的代理
extension HMSinaSelectImageController : UIImagePickerControllerDelegate , UINavigationControllerDelegate{

    //实现协议的方法,一旦实现该方法，需要手动dismiss
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //获取选择的图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
     
        //将图片添加到数组中
        self.imageArray.append(image.suoFangImage(width: UIScreen.main.bounds.width))
        //dismiss控制器
        dismiss(animated: true) {
            
        }
        
        //刷新collectionView
        self.collectionView?.reloadData()
    }

}

//1、定义协议
@objc protocol SelectImageCellDelegate : NSObjectProtocol{

    //2、定义可选的协议方法SelectImageCell
    @objc optional func chooseImage(cell : SelectImageCell?)
    @objc optional func deleteImage(cell : SelectImageCell)

}

//MARK:自定义cell
class SelectImageCell : UICollectionViewCell{

    //4、设置协议对象
    weak var delegate : SelectImageCellDelegate?
    
    var image : UIImage?{
    
        didSet{
        
            //添加按钮的image
            addButton.setImage(image, for: .normal)
            
            if image == nil {
                deletebutton.isHidden = true
            }else{
                deletebutton.isHidden = false
            }
            
        }
    
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //搭建UI界面
    private func setupUI() {
        
        self.contentView.addSubview(addButton)
        self.contentView.addSubview(deletebutton)
        
        //设置约束
        addButton.snp.makeConstraints { (make) in
            
            make.edges.equalTo(self)
            
        }
        
        deletebutton.snp.makeConstraints { (make) in
            
            make.top.right.equalTo(self)
            
        }
        
        //监听按钮的点击事件
        addButton.addTarget(self, action: #selector(clickAddButton), for: .touchUpInside)
        deletebutton.addTarget(self, action: #selector(clickDeleteButton), for: .touchUpInside)
        
    }
    
    @objc private func clickAddButton() {
        
        //让有图片的cell不能点击的方法
        if image != nil {
            return
        }
        
        //跳转到选择图片的控制器,cell中不能完成跳转，应该将事件传递给控制器,用代理
       //5、调用代理方法
         delegate?.chooseImage!(cell: self)
        
    }
    
    @objc private func clickDeleteButton() {
        
        delegate?.deleteImage!(cell: self)
        
    }
    
    //懒加载视图
    lazy var addButton: UIButton = {
        
        let button = UIButton()
        
        //设置图片
        button.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        
        return button
    }()
    
    lazy var deletebutton: UIButton = {
        
        let button = UIButton()
        
        //设置图片
        button.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        button.imageView?.contentMode = .scaleAspectFill
        
        return button
    }()
    
}
